﻿using System.Collections.Generic;
using HtmlAgilityPack;
using System.Linq;

namespace RatingAuthor
{
  internal class CommentsParser : IParser
  {
    private const string RecordsXPath = "/html[1]/body[1]/table[1]";
    private const string PagesCountXPath = "/html[1]/body[1]/center[2]/b[1]";

    public PageData Parse(Page page)
    {
      var root = page.Load().DocumentNode;
      return new PageData
               {
                 PageIndex = page.Index,
                 Records = ParseRecords(root.SelectSingleNode(RecordsXPath)).ToList(),
                 OveralPagesCount = PagesCountParser.Parse(root.SelectSingleNode(PagesCountXPath).InnerText),
               };
    }

    private static IEnumerable<BookRecord> ParseRecords(HtmlNode table)
    {
      while (table.ChildNodes.Count == 6)
      {
        var r = new BookRecord();
        r.SetAuthorUrl(table.ChildNodes[2].ChildNodes[0].Attributes["href"].Value);
        r.SetAuthorUrl(table.ChildNodes[2].ChildNodes[0].Attributes["href"].Value);
        r.SetAuthorName(table.ChildNodes[2].ChildNodes[0].InnerText);
        r.SetUrl(CommentParseBookUrl(table.ChildNodes[1].ChildNodes[0].Attributes["href"].Value));
        r.SetTitle(table.ChildNodes[1].ChildNodes[0].InnerText);
        r.SetSize(table.ChildNodes[1].ChildNodes[2].ChildNodes[0].InnerText);
        r.SetGanres(table.ChildNodes[1].ChildNodes[2].ChildNodes[1].InnerText);
        r.SetCommentsCount(table.ChildNodes[3].ChildNodes[0].InnerHtml.Split('/')[0]);
        yield return r;
        table = table.ChildNodes[5];
      }
    }

    public string IndexedTamplateUrl
    {
      get { return "http://zhurnal.lib.ru/rating/comment/index_comment{0}.shtml"; }
    }
    public string Name
    {
      get { return "Comment"; }
    }
    private static string CommentParseBookUrl(string bookUrl)
    {
      if (bookUrl.StartsWith("/comment"))
        bookUrl = bookUrl.Substring("/comment".Length + 1);

      return  bookUrl;
    }
  }
}